import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:qyou_app/common/api.dart';
import 'package:qyou_app/common/base.dart';
import 'package:qyou_app/common/bloc.dart';
import 'package:qyou_app/page/portal/dynamic/dynamic_all.dart';
import 'package:qyou_app/page/portal/dynamic/dynamic_video.dart';
import 'package:qyou_app/widget/refresh.dart';
import 'package:qyou_app/widget/setting.dart';

class DynamicPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _DynamicPageState();
}

class _DynamicPageState extends State<DynamicPage>
    with Base, SingleTickerProviderStateMixin {
  List tabs = ["视频", "综合"];
  List pages = [DynamicVideoPage(), DynamicAllPagePage()];

  TabController _tabController;
  RefreshController _refreshController;


  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: tabs.length, vsync: this);
    _refreshController = RefreshController(initialRefresh: false);
  }

  //下拉刷新，设置视频加载第一页，将获取的视频数据通知出去
  void _onRefresh() async {
    //1-删除缓存数据
    //2-获取视频数据
    //设置第一页
    BlocProvider.of<VideoPageNoCubit>(context).reset();
    List videoList = await Api.getVideoListData(context, 1);
    BlocProvider.of<VideoCubit>(context).updateVideoData(videoList);
    _refreshController.refreshCompleted();
  }

  //上拉加载
  void _onLoading() async {
    //获取之前加载的数据
    List videoData = BlocProvider.of<VideoCubit>(context).state;
    List videoList = await Api.getVideoListData(context);
    videoData.addAll(videoList);
    BlocProvider.of<VideoCubit>(context).updateVideoData(videoData);
    _refreshController.loadComplete();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        flexibleSpace: Container(
          alignment: Alignment.bottomCenter,
          child: TabBar(
              indicatorColor: Colors.white,//选中下划线的颜色
              indicatorWeight: 3,//选中下划线的高度，值越大高度越高，默认为2
              indicatorSize: TabBarIndicatorSize.label,
              isScrollable: true,//是否需要滚动，true为需要
              unselectedLabelStyle: TextStyle(
                fontSize: 15,
              ),
              unselectedLabelColor: Colors.white70,
              labelStyle: TextStyle(
                fontSize: 18,
              ),
              labelColor: Colors.white,
              controller: _tabController,
              tabs: tabs.map((e) => Tab(text: e)).toList()),
        ),
      ),
      body: TabBarView(
        controller: _tabController,
        children: tabs.asMap().map((i, tab) => MapEntry(i, Builder(
          builder: (context) => Container(
            color: Colors.white,
            child: pages[i],
          ),
        ),),
        ).values.toList(),
      ),
    );
  }
}
